package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.ElectricMeter;
import com.hulman.oms.dao.ElectricMeterDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class ElectricMeterService
{
    @Autowired
    private ElectricMeterDao electricMeterDao;

    public List<ElectricMeter> findElectricMeters(Map<String, Object> map)
    {
        return electricMeterDao.findElectricMeters(map);
    }

    public List<ElectricMeter> findAllElectricMeters()
    {
        Map<String, Object> map = new HashMap<>();
        return electricMeterDao.findElectricMeters(map);
    }

    public Integer findElectricMetersCount(Map<String, Object> map)
    {
        return electricMeterDao.findElectricMetersCount(map);
    }

    public Result findElectricMetersResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = electricMeterDao.findElectricMetersCount(map);
        List<ElectricMeter> data = electricMeterDao.findElectricMeters(map);
        return new Result(data, count);
    }

    public ElectricMeter findElectricMeterById(Integer id)
    {
        return electricMeterDao.findElectricMeterById(id);
    }

    public void saveElectricMeter(ElectricMeter electricMeter)
    {
        if (electricMeter.getRatio() == null)
        {
            electricMeter.setRatio(1);
        }
        if (electricMeter.getId() != null && electricMeter.getId() != 0)
        {
            electricMeterDao.updateElectricMeter(electricMeter);
        } else
        {
            electricMeterDao.insertElectricMeter(electricMeter);
        }
    }

    public void deleteElectricMeterById(Integer id)
    {
        electricMeterDao.deleteElectricMeterById(id);
    }

    public void deleteElectricMeters(int[] ids)
    {
        electricMeterDao.deleteElectricMeters(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importElectricMeters(List<ElectricMeter> meters)
    {
        for (ElectricMeter meter : meters)
        {
            saveElectricMeter(meter);
        }
    }
}
